<template>
  <div class="app-mobile">
    <div class="chat-mobile-container">
      <homeTop :showicon2="true" :showbar8="true"></homeTop>
      <!-- <div>在线人数{{ onlineList.length }}</div> -->
      <div class="chat-mobile-room">
        <div class="message-item-mobile" v-for="(item, index) in messageList" :key="index">
          <div class="flex-left-mobile" v-if="item.userId!== userInfo.userId">
            <div class="avatar-mobile">
              {{ item.userId }}
            </div>
            <div style="margin-left: 10px" class="message-content-mobile">
              <p v-if="item.content" style="font-size: 14px;color: #333;line-height: 1.5;">{{ item.content }}</p>
            </div>
            <div class="message-content-mobile" style="margin-right: 10px">
              <img v-if="item.img" style="width: 100px;height: 100px;border: 1px solid #ccc;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);object-fit: cover;" :src="item.img" alt="">
            </div>
          </div>
          <div v-else class="flex-right-mobile">
            <div class="message-content-mobile" style="margin-right: 10px">
              <p v-if="item.content" style="font-size: 14px;color: #333;line-height: 1.5;">{{ item.content }}</p>
            </div>
            <div class="message-content-mobile" style="margin-right: 10px">
              <img v-if="item.img" style="width: 100px;height: 100px;border: 1px solid #ccc;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);object-fit: cover;" :src="item.img" alt="">
            </div>
            <div class="avatar-mobile">
              {{ item.userId }}
            </div>
          </div>
        </div>
      </div>
      <div class="send-mobile-box">
        <input type="file" @change="handleFileUpload">
        <div style="display: flex;">
          <input class="message-input-mobile" type="text" v-model="yourMessage" @keyup.enter="sendMessage" />
          <el-button class="send-btn-mobile" @click="sendMessage" type="primary">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import homeTop from '@/components/homeTop/index.vue';
import OSS from 'ali-oss';

// 创建OSS客户端
const createOSSClient = () => {
  return new OSS({
    region: 'oss-cn-hangzhou',
    accessKeyId: 'LTAI5tCYF2TAR8tRz4s7BEZj',
    accessKeySecret: '0pxipsBViEUdBF5m8SZfTzceqeFydg',
    bucket: '2202-wd'
  });
};

// 用户信息
const userInfo:any = ref({
  userId: ""
});

// 输入框内容
const yourMessage:any = ref("");
// 消息列表
const messageList:any = ref([]);
// 在线人数列表
const onlineList:any = ref([]);
// WebSocket对象
let ws:any = null;

// 发送消息
const sendMessage = () => {
  if (yourMessage.value) {
    // 打印文本消息
    console.log('发送文本消息：', yourMessage.value);
    ws.send(
      JSON.stringify({
        type: "message",
        userId: userInfo.value.userId,
        content: yourMessage.value
      })
    );
    yourMessage.value = "";
  }
};

// 初始化WebSocket
const initWebsocket = async () => {
  ws = new WebSocket("ws://1.94.217.24:8887/");
  console.log(ws);

  ws.onopen = () => {
    console.log("websocket 连接成功");
    ws.send(
      JSON.stringify({
        type: "init",
        userId: userInfo.value.userId,
        content: "欢迎来到聊天室"
      })
    );
  };

  ws.onerror = () => {
    console.log("websocket 连接失败");
  };

  ws.onmessage = async (data:any) => {
    const message = JSON.parse(data.data);
    switch (message.type) {
      case "tips":
        console.log(message.content);
        break;
      case "message":
        messageList.value.push(message);
        break;
      case "onlineList":
        onlineList.value = message.list;
        break;
      default:
        break;
    }
  };

  ws.onclose = () => {
    console.log("websocket 连接关闭");
  };
};

// 组件挂载时初始化WebSocket
onMounted(async () => {
  userInfo.value.userId = new Date().getTime().toString().slice(8);
  await initWebsocket();
});

// 处理文件上传
const handleFileUpload = async (event:any) => {
  const file:any = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = async (e:any) => {
      const base64Data:any = e.target.result.split(',')[1];
      const blob:any = await fetch(`data:image/jpeg;base64,${base64Data}`).then((r) => r.blob());
      const fileName:any = new Date().getTime() + '.png';
      try {
        const client:any = createOSSClient();
        const result:any = await client.put(fileName, blob);
        // 打印图片消息
        console.log('发送图片消息：', result.url);
        ws.send(
          JSON.stringify({
            type: "message",
            userId: userInfo.value.userId,
            img: result.url
          })
        );
        console.log('上传成功', result);
      } catch (error) {
        console.error('上传失败', error);
      }
    };
    reader.readAsDataURL(file);
  }
};
</script>

<style scoped>
.app-mobile {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.chat-mobile-container {
  width: 100%;
  height: 650px;
  /* overflow: hidden; */
  background: #fff;
  border-radius: 8px;
}

.chat-mobile-room {
  height: calc(100% - 100px);
  padding: 10px;
  box-sizing: border-box;
  overflow: auto;
  background: #f4f4f4;
  bottom: 0px;
}

.message-item-mobile {
  width: 100%;
  margin-bottom: 10px;
}

.flex-left-mobile {
  display: flex;
  justify-content: flex-start;
}

.flex-right-mobile {
  display: flex;
  justify-content: flex-end;
}

.avatar-mobile {
  width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 50%;
  overflow: hidden;
  background: #fafafa;
}

.message-content-mobile {
  min-height: 25px;
  background: #fff;
  border-radius: 8px;
  padding: 8px;
}

.send-mobile-box {
  height: 60px;
  /* display: flex; */
  align-items: center;
  /* margin-top: 20px; */
}

.message-input-mobile {
  height: 40px;
  flex: 1;
}

.send-btn-mobile {
  width: 100px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
</style>